<?php

namespace app\api\controller;

use app\api\model\Users;
use app\api\validate\UserValidate;
use think\facade\Session;
use think\Request;

class Common extends Basic
{
    public function login(Request $request){
        if($request->isPost()){
            $params = $request->param();
            //            验证数据
            $validate = new UserValidate();
            if(!$validate->scene('login')->check($params)) $this->error($validate->getError());
//            执行登录操作
            $resp = $this->checkLogin($params);
            if($resp === false) return $this->error('用户名或密码不正确');
            return $this->success('登录成功！',$resp);
        }
    }

    //    载入注册模板
    public function register(Request $request){
        //    执行注册操作
        if ($request->isPost()){
            $params = $request->param();
//            验证数据
            $validate =  new UserValidate();
            if(!$validate->scene('register')->check($params)) $this->error($validate->getError());
//            执行注册操作
            $resp = $this->writeRegister($params);
            if ($resp["code"] !== 1) return $this->error($resp["msg"]);
//            注册成功
            return $this->success('注册成功！');
        }
    }
    public function isLogin(Request $request){
        if($request->isPost()){
            $token = $request->header('authorization',"");
            if ($token == "") return $this->error('非法访问');
            $resp = checkToken($token);
            if($resp == false) return $this->error('Token已过期！请重新登录');
            return $this->success('验证成功！',$resp);
        }
    }
    //    从数据库验证登录数据
    private function checkLogin($params) {
        $model = new Users();
        $where = [
            ["username|qq|nickname","=",$params['username']],
            ['password',"=",md5($params['password'])]
        ];
//        从数据库查询用户
        $user = $model::where($where)->find();
        if (!$user) return false;
//      生成TOKEN
        $data = [
            "username"=>$user["username"],
            "nickname"=>$user["nickname"],
            'qq'=>$user["qq"],
            'team'=>$user['team'],
            'avatar'      =>    "http://q.qlogo.cn/g?b=qq&nk=".$user['qq']."&s=640",
        ];
//      返回结果
        return ['token'=>createToken($user['id'],$data),'user'=>$data];
    }
//    写入注册数据
    private function writeRegister($params){
        $code = 0;
        $model = new Users();
        //        验证qq号或者用户名是否已经注册
        $user = $model::whereOr([["username","=",$params['username']],["qq","=",$params['qq']]])->find();
        if ($user) {
            $msg = "该用户名或QQ已经被注册";
        }else{
//            写入数据库并登录
            $data = [
                'username'  => $params['username'],
                'password'  => md5($params['password']),
                'sex'       => AttrToSexValue($params['sex']),
                'team'      => AttrToTeamValue($params['team']),
                'nickname'  => $params['nickname'],
                'qq'        => $params['qq']
            ];
            $insert = $model->insertGetId($data);
            if($insert >= 0){
                Session::set("user",["id"=>$insert,"username"=>$params["username"],"nickname"=>$params["nickname"],'qq'=>$params['qq']]);
                $code = 1;
                $msg = "注册成功！";
            }else{
                $msg = "注册失败！服务器错误";
            }

        }
//        返回结果
        return ['code'=>$code,"msg"=>$msg];
    }
}